package com.ruoyi.service.impl;

import com.google.code.kaptcha.Producer;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.utils.sign.Base64;
import com.ruoyi.common.utils.uuid.IdUtils;
import com.ruoyi.service.ICodeService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.FastByteArrayOutputStream;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;

/**
 * 描述：
 */
@Service
@Slf4j
public class CodeServiceImpl implements ICodeService {

    /**
     * 图形验证码图片生成器
     */
    @Resource(name = "captchaProducer")
    private Producer captchaProducer;

    @Override
    public AjaxResult getImgCode(HttpServletResponse response) {
        AjaxResult ajax = AjaxResult.success();
        // 保存验证码信息
        String uuid = IdUtils.simpleUUID();
        String capStr = null, code = null;
        BufferedImage image = null;
        // 生成验证码
        capStr = code = captchaProducer.createText();
//        image = EasyValidateCodeUtil.generateImage(capStr);
//        easyRedisAuthorizationUtil.storageImgCode(uuid, code);
          // 转换流信息写出
        FastByteArrayOutputStream os = new FastByteArrayOutputStream();
        try
        {
            ImageIO.write(image, "jpg", os);
        }
        catch (IOException e)
        {
            return AjaxResult.error(e.getMessage());
        }

        ajax.put("uuid", uuid);
        ajax.put("img", Base64.encode(os.toByteArray()));
        return ajax;
    }

    @Override
    public AjaxResult resetImgCode(String uuid, HttpServletResponse response) {
        return null;
    }

    @Override
    public R<String> getPhoneCode(String phone) {
        return null;
    }

}
